<?php

class TournamentarticlesPage extends BaseAdminPage {

	/**
	 * A verseny azonosítója.
	 *
	 * @var int
	 */
	private $tournamentId;

	function TournamentarticlesPage() {
		parent::BaseAdminPage('TournamentarticlesPage');
	}

	function enterPage() {
		parent::enterPage();

		$this->tournamentId = FunctionLibrary::getGetValueSmart('id', null);
		$_SESSION['__tournamentId'] = $this->tournamentId;

		// definiáljuk a form elemeit
		FormUtil::addForm("newtournamentarticle");
		FormUtil::addFormElement("newtournamentarticle", new FormElementInfo("id_article", "text"));
		FormUtil::addFormElement("newtournamentarticle", new FormElementInfo("id_tournament", "text", $this->tournamentId));
		FormUtil::resetFormValues("newtournamentarticle");

		// engeélyezzük ezeket a browser regisztrációkat
		AdminBase::includeBrowser();
		Browser::registerAllowedBrowserIds('br_article_*');
	}

	function leavePage() {
		parent::leavePage();
			
		AdminBase::includeBrowser();

		Browser::removeAllBrowsers();
		Browser::removeAllowedBrowserIds('br_article_*');

		FormUtil::removeAllForms();
		unset($_SESSION['__tournamentId']);
	}

	protected function _init() {
		$this->tournamentId = FunctionLibrary::getSessionValue('__tournamentId', null);
	}

	public function serveRequest() {
		parent::serveRequest();

		AdminBase::includeBrowser();
		$this->_init();

		$tpl = BaseAdminPage::loadTemplateFile("tournamentarticle.tpl.html");
		TextHandler::insertTextsIntoTemplate($tpl);

		$tpl->setVariable('app_root_url', APP_ROOT_URL);

		$articles = SiteDBHelper::getTournamentArticles($this->tournamentId, AdminBase::getCurrentEditlang());
		if(is_null($articles)) {
			// suxxx!
			handleError(TextHandler::getText('err_readrecordsfailed'));
			$tpl->replaceBlock('tournamentarticle', ' ', false);
			$tpl->touchBlock('tournamentarticle');
		} else {
			// megvannak a rekordok!

			$action = FunctionLibrary::getGetValue('action');
			if($action) {
				$action = 'action_'.$action;
				$this->$action();
			}

			// kell a hozzáadás művelet
			FormUtil::insertFormValuesToTemplate("newtournamentarticle", $tpl);
			$tpl->setVariable('addFormAction', LinkProvider::getLink('addTournamentArticle'));
			$browserLink = $this->getFCKBrowserUrls($this->tournamentId);
			$tpl->setVariable('link_browser', $browserLink);

			if(count($articles) == 0) {
				$tpl->replaceBlock('tournamentarticle', ' ', false);
				$tpl->touchBlock('tournamentarticle');
			} else {
				foreach($articles as $record) {
					$tpl->setCurrentBlock("tournamentarticle");

					$trClasses = array();

					$tpl->setVariable("but_setdefault", TextHandler::getText('but_setdefault'));
					$tpl->setVariable("but_delete", TextHandler::getText('but_delete'));
					$tpl->setVariable('app_root_url', APP_ROOT_URL);

					$tpl->setVariable("link_del", LinkProvider::getLink("delTournamentArticle", array("id" => $record['id'])));
					$tpl->setVariable("link_setdefault", LinkProvider::getLink("defaultTournamentArticle", array("id" => $record['id'])));
					if ($record['isdefault']) {
						$tpl->setVariable('hidden', 'hidden');
						$trClasses[] = "default";
					} else {
						$tpl->setVariable('hidden', '');
					}
					$tpl->setVariable("tr_class", implode($trClasses, " "));

					$tpl->setVariable("id", $record['id']);

					// nem áll szerkesztés alatt
					if ($record['langcode'] == AdminBase::getCurrentEditlang()) {
						$tpl->setVariable("title", $record['title']);
					} else {
						$tpl->setVariable("title", '['.$record['title'].'] *');
					}
					$articleUrls = ContentUrlManager::getArticleUrls(SiteHandler::getCurrentSiteId(), intval($record['id']), AdminBase::getCurrentEditlang(), "full");
					if(is_null($articleUrls))
						$articleUrls = array();
					$directLinksSrc = array();
					foreach($articleUrls as $aurl) {
						array_push($directLinksSrc, "<a href='$aurl' target='_blank'>$aurl</a>");
					}
					
					$tpl->setVariable("href", implode("<br/>", $directLinksSrc));

					$tpl->parseCurrentBlock();
				}
			}
		}

		return $tpl->get();
	}

	/**
	 * CygnusFCKEditor-nak átadandó browserUrl-ek összeállítása.
	 * Lehet h egy másik cikk típusban másképpen akarjuk...
	 *
	 * @return array
	 */
	protected function getFCKBrowserUrls($id) {
		// browser beállítások
		$linkBrowserUrl = HydraLinkProvider::getLink("newBrowserURL", array("id"=>"br_article_".$id, "cfg"=>"tournament_link", "langcode"=>TextHandler::getCurrentLangcode(), "target"=>Browser::TARGET_POPUP_JSCALLBACK));
		$ownUploadsIniParams = array("postfix"=>$id);
		$linkBrowserUrl = BrowserContentManager::encodeIniParamsToUrl("own", $ownUploadsIniParams, $linkBrowserUrl);

		return $linkBrowserUrl;
	}

	/**
	 * Töröl.
	 */
	private function action_delTournamentArticle() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		$id = FunctionLibrary::getGetValueSmart("id", null);
		if(! empty($id) && is_numeric($id)) {
			$id = intval($id);

			// próbáljuk törölni!
			try {
				AdminDBHelper::delTournamentArticle($this->tournamentId, $id);

				handleSuccess(TextHandler::getText("compa_del_success"), HydraLinkProvider::getLink("link_tournamentarticle"));
				exit();
			} catch (Exception $e) {
				$logErrorString = "removing tournamentarticle id_tournament=$this->tournamentId,id_article=$id failed";
				$errorStrings = array($e->getMessage());
			}
		} else {
			// na hát ez azért fura lenne...
			$logErrorString = "required request parameter 'id' is missing";
			$errorStrings = array(TextHandler::getText("err_unknown"));
		}

		Log::error('following errors occured during operation: '.$logErrorString);
		handleError(TextHandler::getParsedText("compa_del_err", array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), HydraLinkProvider::getLink("link_tournamentarticles"));
		exit();
	}

	/**
	 * Alapértelmezetté tesz.
	 */
	private function action_defaultTournamentArticle() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		$id = FunctionLibrary::getGetValueSmart("id", null);
		if(! empty($id) && is_numeric($id)) {
			$id = intval($id);

			// próbáljuk alapértelmezetté tenni!
			try {
				AdminDBHelper::defaultTournamentArticle($this->tournamentId, $id);

				handleSuccess(TextHandler::getText("compa_default_success"), HydraLinkProvider::getLink("link_tournamentarticle"));
				exit();
			} catch (Exception $e) {
				$logErrorString = "setting default tournamentarticle id_tournament=$this->tournamentId,id_article=$id failed";
				$errorStrings = array($e->getMessage());
			}
		} else {
			// na hát ez azért fura lenne...
			$logErrorString = "required request parameter 'id' is missing";
			$errorStrings = array(TextHandler::getText("err_unknown"));
		}

		Log::error('following errors occured during operation: '.$logErrorString);
		handleError(TextHandler::getParsedText("compa_default_err", array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), HydraLinkProvider::getLink("link_tournamentarticles"));
		exit();
	}

	/**
	 * Hozzáad.
	 */
	private function action_addTournamentArticle() {
		AdminPageHelper::action_add($this, 'addTournamentArticle', 'newtournamentarticle', 'tournamentarticle', "compa_add_success", "compa_add_err", "link_tournamentarticle");
	}

	public function checkData($type, $values) {
	}

}
?>